/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.proyectofinal.ramas.controller;

import com.proyectofinal.ramas.domain.Company;
import com.proyectofinal.ramas.domain.UserRole;
import com.proyectofinal.ramas.domain.UserRolePK;
import com.proyectofinal.ramas.service.CompanyService;
import com.proyectofinal.ramas.service.RoleService;
import com.proyectofinal.ramas.service.UserImpl;
import com.proyectofinal.ramas.service.UserRoleService;
import com.proyectofinal.ramas.service.UserRoleStatusService;
import com.proyectofinal.ramas.service.UserService;
import com.proyectofinal.ramas.service.UserStatusService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author nicolas
 */
@Controller
@SessionAttributes("currentUserRole")
public class MainController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserStatusService userStatusService;
    @Autowired
    private UserRoleStatusService userRoleStatusService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private CompanyService companyService;

    @RequestMapping(value = "/user-login", method = RequestMethod.GET)
    public ModelAndView loginForm() {
        return new ModelAndView("login-form");
    }

    @RequestMapping(value = "/error-login", method = RequestMethod.GET)
    public ModelAndView invalidLogin() {
        ModelAndView modelAndView = new ModelAndView("login-form");
        modelAndView.addObject("error", true);
        return modelAndView;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String homePage(Model model) {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            String userName = auth.getName();
            model.addAttribute("userName", userName);
            List<UserRole> roles = userRoleService.getAll(userService.get(userName));
            model.addAttribute("roles", roles);
            //model.addAttribute("roleAttribute", new Object());
        }

        return "home";
    }
    @RequestMapping(value = "/menu", method = RequestMethod.GET)
    public String menuPageBack(Model model,
            @ModelAttribute("currentUserRole") UserRole currentUserRole) {
        String page = "";
        
        switch(currentUserRole.getUserRolePK().getRole().getRoleID().intValue()){
            case 1: 
                page = "adminMenu";
                break;
            case 2: 
                page = "clientMenu";
                break;   
        }
        return page;
    }

    @RequestMapping(value = "/menu", method = RequestMethod.POST)
    public String menuPage(Model model,
            @RequestParam("roleID") Integer roleID,
            @RequestParam("companyID") Integer companyID) {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        UserImpl user = (UserImpl) auth.getPrincipal();
        String page = "";

//        Si el usuario posee mas de un Rol (o no se asignó ninguna companía), 
//        se utiliza la opción seleccionada para determinar el Rol con el cuál ingresará

        if (auth.getAuthorities().size() > 1 || user.getCompany() == null) {

            Company company = companyService.get(companyID);
            user.setCompany(company);

            List authoritiesNew = new ArrayList();

            switch (roleID.intValue()) {

                case 1:
                    authoritiesNew.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                    break;
                case 2:
                    authoritiesNew.add(new SimpleGrantedAuthority("ROLE_CLIENT"));
                    break;
            }

            Authentication authNew = new UsernamePasswordAuthenticationToken(user, user.getPassword(), authoritiesNew);
            SecurityContextHolder.getContext().setAuthentication(authNew);
        }

        auth = SecurityContextHolder.getContext().getAuthentication();
        user = (UserImpl) auth.getPrincipal();
        String userName = auth.getName();
        String currentRole = auth.getAuthorities().iterator().next().toString();
        Integer currentRoleID = (currentRole.compareTo("ROLE_ADMIN") == 0) ? Integer.valueOf("1") : Integer.valueOf("2");

        switch (currentRoleID.intValue()) {

            case 1:
                page = "adminMenu";
                break;
            case 2:
                page = "clientMenu";
                break;
        }
        UserRole userRole = userRoleService.get(new UserRolePK(userService.get(userName), roleService.get(currentRoleID), user.getCompany()));
        model.addAttribute("currentUserRole", userRole);   

        return page;

    }
    

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView indexPage() {

        return new ModelAndView("home");
    }
}
